//
//  QAZoneViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/26.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "QAZoneViewController.h"
#import "Question.h"
#import "PostQuestionViewController.h"
//#import "QAZoneTableViewCell.h"
#import "QATableViewCell.h"
#import "QADetailViewController.h"

@interface QAZoneViewController ()<UITableViewDelegate, UITableViewDataSource, UISearchBarDelegate>

@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@property (nonatomic, strong) NSString *keyWord;

@property (nonatomic, assign) NSInteger isPush;

@end

@implementation QAZoneViewController {
    UITableView *_tableView;
    //    QAZoneTableViewCell *_cell;
    UILabel     *_noThings;
    UISearchBar *_searchBar;
    UIView      *_maskView;
}

- (void)viewWillAppear:(BOOL)animated {
    
    if (self.isSearch) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchQA:)name:@"searchQA" object:nil];
        
    }
    
    // 当当前页面顶部位置
    if (self.page == 1) {
        [self GETQAList];
    }
    self.isPush = 0;
}

- (void)viewDidDisappear:(BOOL)animated {
    if (self.isSearch && self.isPush == 0) {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"searchQA" object:nil];
    }
}
// 主页tableView是否滚动接收到通知
- (void)searchQA:(NSNotification *)notification {
    self.keyWord = notification.userInfo[@"keyWord"];
    
    NSLog(@"－－－－－问答搜索接收到通知------\n = %@", self.keyWord);
    
//    _noThings.hidden = YES;

    [self GETQAList];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
    self.keyWord = @"";
    
    [self buildUI];
    
    if (!self.isSearch) {
        [self GETQAList];
    }
    
    [self refreshData];
    
}


#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = kWhiteColor;
    
    if (!self.isSearch && !self.type) {
        
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(SW(20), SW(40), SCREEN_WIDTH-SW(10), SW(10))];
        _searchBar.keyboardType = UIKeyboardTypeDefault;
        _searchBar.delegate = self;
        // 底部的颜色
        _searchBar.barTintColor = [UIColor whiteColor];
        _searchBar.layer.borderWidth = 1;
        _searchBar.layer.borderColor = RGBA(236, 236, 236, 1).CGColor;
        _searchBar.layer.cornerRadius = SW(20);
        _searchBar.layer.masksToBounds = YES;
        _searchBar.searchBarStyle = UISearchBarStyleDefault;
        _searchBar.barStyle = UIBarStyleBlack;
        [self.view addSubview:_searchBar];
//        [_searchBar becomeFirstResponder];
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SW(20)*3, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-49-SW(20)*3) style:UITableViewStylePlain];
        _maskView = [[UIView alloc] initWithFrame:_tableView.frame];
        _maskView.backgroundColor = RGBA(0, 0, 0, 0.2);
        _maskView.hidden = YES;
        [_maskView addTarget:self action:@selector(maskClick)];
        
    }
    else {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-49-1) style:UITableViewStylePlain];
    }
    
//    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-49-1) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.rowHeight = UITableViewAutomaticDimension;
    _tableView.estimatedRowHeight = 440;
    [_tableView registerClass:[QATableViewCell class] forCellReuseIdentifier:@"cell"];
    
    
    UIButton *postBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:postBtn];
    [postBtn setImage:IMAGE(@"icon_qna_fabu") forState:UIControlStateNormal];
    [postBtn setTitle:@" 发布问题" forState:UIControlStateNormal];
    [postBtn setBackgroundColor:UIMainColorRGB];
    postBtn.titleLabel.font = kUHSystemFontWithSize(14);
    postBtn.frame = CGRectMake(0, SCREEN_HEIGHT-49-64-44, SCREEN_WIDTH, 49);
    [postBtn addTarget:self action:@selector(postClicK:) forControlEvents:UIControlEventTouchUpInside];
    
    if (self.isSearch) {
        postBtn.hidden = YES;
        _tableView.frame = CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-64-49-1);
    }
    
    if (self.type) {
        postBtn.hidden = YES;
        _tableView.frame = CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-(44+[LZCTools textSizeWithText:@"x" font:kUHSystemFontWithSize(14)].height*3+15+4*SW(15)));
    }
    
    _noThings = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-(65+SW(20)*3))];
    [self.view addSubview:_noThings];
    _noThings.text = @"没有相关资源";
    _noThings.textAlignment = NSTextAlignmentCenter;
    _noThings.backgroundColor = self.view.backgroundColor;
    _noThings.hidden = YES;
    
    [self.view addSubview:_maskView];

}

- (void)maskClick {
    [_searchBar resignFirstResponder];
    self.keyWord = _searchBar.text;
    self.page = 1;
    [self GETQAList];
}


#pragma mark ==========UISearchBar 代理响应方法==========
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    return YES;
}
//- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
//    return YES;
//}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    NSLog(@"开始输入搜索内容");
    
    _maskView.hidden = NO;
    
    // 取消字体颜色？
    searchBar.showsCancelButton = YES;
    [searchBar setShowsCancelButton:YES animated:YES];
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length == 0) {
        self.keyWord = @"";
        [self searchB];
    }
    
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
    NSLog(@"输入搜索完毕");
    
    _maskView.hidden = YES;
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"取消搜索");
    
    [searchBar setShowsCancelButton:NO animated:YES];
    [searchBar resignFirstResponder];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"搜索");
    
    [searchBar resignFirstResponder];
    
    NSString *word = [searchBar.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if (word.length == 0) {
        [self presentViewController:[LZCTools alertMessage:@"请输入关键字"] animated:YES completion:nil];
        return;
    }
    
    self.page = 1;
    self.keyWord = word;
    
    if (self.keyWord.length > 6) {
        self.keyWord = [self.keyWord substringToIndex:6];
    }
    
    _searchBar.text = self.keyWord;
    
    [self searchB];
}

- (void)searchB {
    
    [self GETQAList];
}


#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETQAList];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETQAList];
    }];
    
}


#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QATableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    Question *model = self.infoArr[indexPath.row];
    
    cell.model = model;
    
    cell.qaBtn.tag = indexPath.row+1;
    [cell.qaBtn addTarget:self action:@selector(postAnswer:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}
//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    CGFloat cellH = [_cell cellHeight];
//    if (cellH == 0) {
//        return 10;
//    }
//    else
//        return [_cell cellHeight];
//}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
    
    self.isPush = 1;
    
    Question *model = self.infoArr[indexPath.row];
    
    QADetailViewController *detailVC = [[QADetailViewController alloc] init];
    detailVC.answerId = [NSString stringWithFormat:@"%ld", model.qId];
    
    [self.navigationController pushViewController:detailVC animated:YES];
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.1;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.1)];
    view.backgroundColor = UISeparatedColorRGB;
    return view;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView * view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.1)];
    view.backgroundColor = UISeparatedColorRGB;
    return view;
}



#pragma mark ===========响应方法==========
- (void)postAnswer:(UIButton *)sender {
    NSLog(@"直接进入发布答案页面");
    
    self.isPush = 1;
    
    Question *model = self.infoArr[sender.tag-1];
    
    QADetailViewController *detailVC = [[QADetailViewController alloc] init];
    detailVC.answerId = [NSString stringWithFormat:@"%ld", model.qId];
    detailVC.isComment = @"1";
    
    [self.navigationController pushViewController:detailVC animated:YES];

}

/**
 获取资讯列表
 */
- (void)GETQAList {
    
    // GET /articles 获取（查询）资讯列表 keyword 关键词，匹配商品名 page 页码，默认为1 per_page 每页显示数，默认为10 cate_id 二级分类ID，暂不支持一级分类搜索 orderby 排序字段
    
    NSDictionary *param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
        @"per_page":@"10"};
    NSString *url = APIQuestions;
    NSString *name = @"获取问题列表";
    
    if (self.type) {
        if (self.type == 1) {
            param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                      @"per_page":@"10",
                      @"user_id":self.user_id};
//            name = @"获取我的问题列表";
        }
        else if (self.type == 2) {
            param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                      @"per_page":@"10"};
            url = [NSString stringWithFormat:@"%@/%@/answered-questions", APIUser, self.user_id];
//            name = @"获取我的回答";
        }
    }
    else {
        param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                  @"per_page":@"10",
                  @"keyword":self.keyWord};
    }
    
    
    if (self.isSearch) {
        if (self.keyWord.length == 0) {
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            return;
        }
        param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                  @"per_page":@"10",
                  @"keyword":self.keyWord};
        //        name = @"搜索问答";
    }
    
    [[NetworkTool sharedTool] requestWithName:name URLString:url parameters:param method:@"GET" callBack:^(id responseObject) {
        
        
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        _noThings.hidden = YES;
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
            
            // 所有的逻辑显示
            if (self.isSearch) {
                [_tableView.mj_footer endRefreshing];
//                [MBProgressHUD hideHUDForView:self.view animated:YES];
//                [LZCTools HUDMessage:@"没有这个问答" delay:1.5f];
                if (self.infoArr.count == 0) {
                    _noThings.hidden = NO;
                }
            }
        }
        
        for (NSDictionary *dic in arr) {
            Question *model = [[Question alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        NSLog(@"name = %@ num = %ld", name, self.infoArr.count);
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
    
}

- (void)postClicK:(UIButton *)sender {
    if (GetUserDefaule(USERINFO) == NULL) {
        [self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
        return;
    }
    NSLog(@"点击发布问题");
    PostQuestionViewController *postVC = [[PostQuestionViewController alloc] init];
    [self.navigationController pushViewController:postVC animated:YES];
    
}

// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
